package com.kuaidian.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kuaidian.model.api.ResponseMsg;
import com.kuaidian.service.RedisService;
import com.kuaidian.util.constant.ErrorCode;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	
    
	@Autowired
	private RedisService redisService; 
	
	
	 @Override
	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {

		 	
		 	if (request.getRequestURI().indexOf("api-docs") > -1) {
				return true;
			}
		 	//注册时验证手机号 注册 登录 文件上传
		 	if (request.getRequestURI().indexOf("client") > -1 || request.getRequestURI().indexOf("fileUpload") > -1) {
				return true;
			}
		 	
		 	//MIS系统
		 	if (request.getRequestURI().indexOf("MIS_SYS") > -1) {
//		 		String userName = request.getParameter("userName");
//		 		HttpSession session = request.getSession(true);
//		 		String session_name = (String) session.getAttribute("userName");
//		 		if(StringUtil.isBlank(userName) || StringUtil.isBlank(session_name) || !userName.equals(session_name)){
//		 			return false;
//		 		}
		 		return true;
			}
		 	
		 	String user_id = request.getParameter("user_id");
		 	String token = request.getParameter("token");
		 	
		 	if(StringUtil.isBlank(user_id) || StringUtil.isBlank(token) || !token.equals(redisService.getCachedLoginedUser(new Integer(user_id)))){
		 		//验证失败
	            ResponseMsg retMsg = new ResponseMsg("需要重新登陆", ErrorCode.INVALID_SID, null);
	    	    String jsonString =JacksonMgr.toJSON(retMsg);

	            response.setHeader("Content-type", "application/json;charset=UTF-8");  
	            response.setCharacterEncoding("UTF-8");  
	            try {
	    			response.getWriter().print(jsonString);
	    		} catch (IOException e) {
	    			e.printStackTrace();
	    		}
	           return false;
		 	}else{
		 		return true;
		 	}
	     }
	
	
}
